import io
import random

import oss2
import requests
import yaml
from PIL import Image, ImageDraw, ImageOps
from qcloud_cos import CosConfig, CosS3Client


# 获取阿里云OSS图片的url，自行选择
def get_oss_image_url():
    # 读取YAML配置文件
    with open('resource/oss.yaml', 'r', encoding='utf-8') as file:
        config = yaml.safe_load(file)

    oss_config = config['oss']
    oss_access_key_id = oss_config['access_key_id']
    oss_access_key_secret = oss_config['access_key_secret']
    endpoint = oss_config['endpoint']
    bucket_name = oss_config['bucket_name']
    dir_name = oss_config['dir_name']

    # 创建OSS客户端
    auth = oss2.Auth(oss_access_key_id, oss_access_key_secret)
    bucket = oss2.Bucket(auth, endpoint, bucket_name)

    # 列举Bucket中的文件
    def list_files(buckets, prefix):
        for obj in oss2.ObjectIterator(buckets, prefix=prefix):
            yield obj.key

    # 获取文件列表
    files = list(list_files(bucket, dir_name))[1:]

    # 随机获取一个文件的key
    random_key = random.choice(files)
    return f'https://{bucket_name}.{endpoint}/{random_key}'


# 获取腾讯云COS图片的url，自行选择
def get_cos_image_url():
    # 读取YAML配置文件
    with open('resource/cos.yaml', 'r', encoding='utf-8') as file:
        config = yaml.safe_load(file)

    cos_config = config['cos']
    cos_access_key_id = cos_config['access_key_id']
    cos_access_key_secret = cos_config['access_key_secret']
    endpoint = cos_config['endpoint']
    bucket_name = cos_config['bucket_name']
    dir_name = cos_config['dir_name']
    custom_domain = cos_config.get('custom_domain', f'{bucket_name}.cos.{endpoint}.myqcloud.com')

    # 初始化 COS 配置
    cos_config = CosConfig(Region=endpoint, SecretId=cos_access_key_id, SecretKey=cos_access_key_secret)
    cos_client = CosS3Client(cos_config)

    # 列举Bucket中的文件
    def list_files(client, bucket_name, prefix):
        response = client.list_objects(Bucket=bucket_name, Prefix=prefix)
        for obj in response.get('Contents', []):
            yield obj['Key']

    # 获取文件列表
    files = list(list_files(cos_client, bucket_name, dir_name))[1:]

    # 随机获取一个文件的key
    random_key = random.choice(files)
    return f'https://{custom_domain}/{random_key}'


# 获取图片数据
def get_image_data(img_url):
    response = requests.get(img_url)
    if response.status_code == 200:

        img = Image.open(io.BytesIO(response.content))

        # 原始图片的宽度和高度
        original_width, original_height = img.size

        # 新的高度
        new_height = 900

        # 计算新的宽度，保持比例
        new_width = int(original_width * new_height / original_height)

        # 调整图片大小
        resized_img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)

        # 创建一个带有圆角的图片
        mask = Image.new('L', resized_img.size, 0)
        draw = ImageDraw.Draw(mask)
        corner_radius = 20
        draw.rounded_rectangle([(0, 0), resized_img.size], corner_radius, fill=255)
        rounded_img = ImageOps.fit(resized_img, mask.size, centering=(0.5, 0.5))
        rounded_img.putalpha(mask)

        return rounded_img
    else:
        return "Image not found", 404
